<template>
  <div class="app-container home">
    <div class="map" style="display: flex">
      <div style="width: 80%; height: 100%;" id="allmap" ref="allmap"></div>
      <div style="width: 20%; height: 100%; padding: 20px;">
        <el-card class="box-card" style="width: 100%; height: calc(50% - 10px); margin-bottom: 20px;">
          <div slot="header" class="clearfix" >
            <i class="el-icon-money"></i>
            <span style="margin-left: 10px;">今日交易概况</span>
          </div>
          <div id="transactionOverview">
            <div class="text item">
              充电金额：<span class="value">{{ chargingAmount }}</span>
            </div>
            <div class="text item">
              充电笔数：<span class="value">{{ chargingCount }}</span>
            </div>
            <div class="text item">
              充值金额：<span class="value">{{ rechargingAmount }}</span>
            </div>
            <div class="text item">
              充值笔数：<span class="value">{{ rechargingCount }}</span>
            </div>
          </div>
        </el-card>
        <el-card class="box-card" style="width: 100%; height: calc(50% - 10px);">
          <div slot="header" class="clearfix" >
            <i class="el-icon-location-outline"></i>
            <span style="margin-left: 10px;">充电桩概况</span>
          </div>
          <div class="text item" style="font-size: 16px; margin-bottom: 10px;">
            正在充电：<span class="value">{{ ChargingNum }}</span>
          </div>
          <div class="text item" style="font-size: 16px; margin-bottom: 10px;">
            当前空闲：<span class="value">{{ AvailableNum }}</span>
          </div>
          <div class="text item" style="font-size: 16px; margin-bottom: 10px;">
            设备离线：<span class="value">{{ OutLineNum }}</span>
          </div>
          <div class="text item" style="font-size: 16px; margin-bottom: 10px;">
            设备故障：<span class="value">{{ ErrorNum }}</span>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>
<script>
import { AllChargingpilesstation } from "@/api/system/chargingpilesstation";
import { getAnalyse ,getTrans} from "@/api/system/chargingpiles";
import IconImg from '@/assets/images/loc.png'
import axios from 'axios'; // 引入 axios 库
export default {
  data() {
    return {
      ChargingNum: 0,
      AvailableNum: 0,
      OutLineNum: 0,
      ErrorNum: 0,
      chargingAmount: 0,
      chargingCount: 0,
      rechargingAmount: 0,
      rechargingCount: 0
    }
  },

  async mounted() {
    try {
      const response = await this.getTranses();
      console.log(response)
      const summary = response; // 假设后端返回的数据是正确的格式
      this.chargingAmount = summary.chargingAmount;
      this.chargingCount = summary.chargingCount;
      this.rechargingAmount = summary.rechargingAmount;
      this.rechargingCount = summary.rechargingCount;
      await this.loadBaiduMapScript();
      const map = new BMapGL.Map(this.$refs.allmap); // 创建地图实例
      const defaultPoint = new BMapGL.Point(112.9364, 28.2351); // 长沙市岳麓区的经纬度
      this.initMap(map, defaultPoint);

      // 获取充电站数据
      const chargingStations = await this.getChargingStations();
      this.addChargingStationsToMap(map, chargingStations);

      //获取分析数据
      const analyseData = await this.getAnalysis();
      console.log(analyseData);
      this.ChargingNum = analyseData.data.chargingNum;
      this.AvailableNum = analyseData.data.availableNum;
      this.OutLineNum = analyseData.data.outLineNum;
      this.ErrorNum = analyseData.data.errorNum;

      // 启用和配置定位功能
      const geolocation = new BMapGL.Geolocation();
      geolocation.getCurrentPosition((r) => {
        if (geolocation.getStatus() === BMAP_STATUS_SUCCESS) {
          const point = r.point;
          map.centerAndZoom(point, 19); // 将地图中心移动到用户位置


          // 显示用户坐标
          const coordDisplay = document.createElement('div');
          coordDisplay.style.position = 'absolute';
          coordDisplay.style.bottom = '10px';
          coordDisplay.style.left = '10px';
          coordDisplay.style.padding = '5px 10px';
          coordDisplay.style.backgroundColor = 'rgba(0,0,0,0.5)';
          coordDisplay.style.color = 'white';
          coordDisplay.style.zIndex = '999';
          coordDisplay.innerHTML = `经度: ${point.lng.toFixed(6)}, 纬度: ${point.lat.toFixed(6)}`;
          this.$refs.allmap.appendChild(coordDisplay);

          // 监听地图的鼠标移动事件
          map.addEventListener('mousemove', function (e) {
            const lng = e.latlng.lng.toFixed(6);
            const lat = e.latlng.lat.toFixed(6);
            coordDisplay.innerHTML = `经度: ${lng}, 纬度: ${lat}`;
          });



        } else {
          alert('定位失败: ' + geolocation.getStatus());
          this.initMap(map, defaultPoint); // 使用默认位置初始化地图
        }
      }, {enableHighAccuracy: true});

    } catch (error) {
      console.error('百度地图脚本加载失败:', error);
      alert('地图加载失败，请检查网络连接');
    }
  },
  methods: {
    loadBaiduMapScript() {
      return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'http://api.map.baidu.com/getscript?type=webgl&v=1.0&ak=Cu658Y9xQy2UXxD1pKwNM3lD5KxAbMSm';
        script.onload = resolve;
        script.onerror = reject;
        document.head.appendChild(script);
      });
    },
    initMap(map, point) {
      map.centerAndZoom(point, 19); // 初始化地图，设置中心点坐标和地图级别
      map.enableScrollWheelZoom(false); // 开启鼠标滚轮缩放
      map.setHeading(64.5); // 设置地图旋转角度
      map.setTilt(73); // 设置地图的倾斜角度

      const scaleCtrl = new BMapGL.ScaleControl(); // 添加比例尺控件
      const hahaCtrl = new BMapGL.LocationControl();//添加定位控件
      const cityCtrl = new BMapGL.CityListControl();//添加选择城市控件
      map.addControl(cityCtrl);
      map.addControl(scaleCtrl);
      map.addControl(hahaCtrl);

    },
    async getChargingStations() {
      try {
        const response = await AllChargingpilesstation();
        return response.data; // 假设 API 返回的数据格式为 { data: [...] }
      } catch (error) {
        console.error('获取充电站数据失败:', error);
        return [];
      }
    },
    getAnalysis(){
      return getAnalyse();
    },
    getTranses(){
      return getTrans();
    },
    addChargingStationsToMap(map, stations) {
      const iconSize = new BMapGL.Size(50, 50); // 假设你的图标是50x50像素
      const iconImage = IconImg;
      const myIcon = new BMapGL.Icon(iconImage, iconSize);

      console.log(myIcon)
      stations.forEach(station => {
        const [longitude, latitude] = station.address.split(';').map(Number);
        const point = new BMapGL.Point(longitude, latitude);
        var label = new BMapGL.Label(station.sname, {
          position: point,
          offset: new BMapGL.Size(20, -10) // 调整文字备注的位置
        });
        const marker = new BMapGL.Marker(point,{icon: myIcon}); // 创建标注
        marker.addEventListener("click", function(){
          alert(
            "充电站："+station.sname+
            "设备数："+station.number+
            "当前可用："+(station.number-station.use)
          );
        });
        marker.setLabel(label);
        map.addOverlay(marker); // 将标注添加到地图中
      });
    }
  }
};
</script>

<style scoped lang="scss">
.app-container {
  font-family: "Arial", sans-serif;
}
.map {
  width: 100%;
  height: 500px; /* 确保容器有高度 */
  background-color: #f0f0f0; /* 添加背景色以便于调试 */
}

.home {
  blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 17.5px;
    border-left: 5px solid #eee;
  }

  hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eee;
  }

  .col-item {
    margin-bottom: 20px;
  }

  ul {
    padding: 0;
    margin: 0;
  }

  font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;

  ul {
    list-style-type: none;
  }

  h4 {
    margin-top: 0px;
  }

  h2 {
    margin-top: 10px;
    font-size: 26px;
    font-weight: 100;
  }

  p {
    margin-top: 10px;

    b {
      font-weight: 700;
    }
  }

  .update-log {
    ol {
      display: block;
      list-style-type: decimal;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0;
      margin-inline-end: 0;
      padding-inline-start: 40px;
    }
  }

  .map-container {
    width: 100%;
    height: 400px; /* 确保容器有高度 */
    overflow: hidden; /* 防止滚动条出现（如果需要的话） */
  }
  .box-card {
    background-color: white;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
  }

  .text.item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }

  .value {
    font-weight: bold;
    color: #409eff;
  }

  .clearfix i {
    color: #409eff;
  }
}
</style>
